var form = layui.form,
    laydate = layui.laydate,
    upload = layui.upload,
    annexList = [],
    table = layui.table,
    $ = layui.jquery,
    id = getQueryVariable("id"),
    //采购付款权限 默认为无
    isProcurementPayment = true;

layui.use(['tableEdit'], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer;

    //明细数据
    let detailList = [];
    //付款类型
    let type = "";
    //币种
    let currencyInfo = [];
    //美元编码
    let usdCode = "";
    //美元
    let usdName = "";
    //美金汇率
    let usdRate = "";
    //美金对人名币汇率
    let rmbRate = "";
    //公司信息
    let companyInfo = [];
    //付款类型
    let paymentTypeList = [];
    //所有用户
    let userList = [];
    //银行信息
    let bankList = [];
    //供应商信息
    let supplierList = [];

    layer.ready(function () {

        //采购付款权限 有该标签:false 无该标签:true
        isProcurementPayment = getAllRolesByCurr("ProcurementPayment");

        //获取所有公司信息
        $.ajax({
            url:"receivePayment/getCompanyInfo",
            success:function(data){
                if(data.status == 200){
                    companyInfo = data.data;
                    let initCode = "";
                    let initName = "";
                    for(let i in data.data){
                        if(data.data[i].isProxy == 1){
                            initCode = data.data[i].code;
                            initName = data.data[i].name;
                        }
                        //公司名称
                        $('#companyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    if(initCode.length > 0){
                        $('#companyCode').val(initCode);
                        $('#companyName').val(initName);
                    }
                    form.render('select');
                }
            }
        });
        //获取当前登陆用户名称
        $("#operationNo").val(user.name);

        //获取币种
        $.ajax({
            url:"receivePayment/getCurrencyInfo",
            success:function(data){
                if(data.status == 200){
                    currencyInfo = data.data;
                    for(let i in data.data){
                        if(data.data[i].englishName == "RMB"){
                            //RMB编码
                            usdCode = data.data[i].code;
                            //RMB名称
                            usdName = data.data[i].name;
                            //RMB兑美元汇率
                            usdRate = data.data[i].exchangeRate;
                            $("#usdRate").val(usdRate);
                        }else if(data.data[i].englishName == "USD"){
                            //获取美金兑人名币汇率
                            rmbRate = data.data[i].exchangeRate;
                        }
                        $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    if(usdCode.length > 0){
                        //默认RMB选中
                        $('#currencyCode').val(usdCode);
                        $('#currency').val(usdName);
                        //RMB汇率为1
                        $('#rmbRate').val(1);
                    }
                    form.render('select');
                }
            }
        });

        //获取付款类型
        $.ajax({
            url:"payment/getPaymentTypeInfo",
            success:function(data){
                if(data.status == 200){
                    paymentTypeList = data.data;
                }
            }
        });

        //获取所有用户信息
        $.ajax({
            url:"otherOutStock/getAllUserInfo",
            success:function(data){
                if(data.status == 200){
                    userList = data.data;
                }
            }
        });

        //获取供应商信息
        $.ajax({
            url:"payment/getSupplierInfo",
            success:function(data){
                if(data.status == 200){
                    supplierList = data.data;
                    for(let i in data.data){
                        $('#supplierCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //收款编号：RTCO+yyyyMMdd+3位自动
        let billNo = "RTCO" + getNowFormatDate(2);
        $("#billNo").val(billNo);

        form.render();
    })

    //监听币种下拉框
    form.on('select(currencyCode)', function (data) {
        if(data.value === ""){
            return;
        }
        let englishName = getCurrencyInfoByCode(data.value, 1);
        if(englishName == "RMB"){
            //如果选择rmb，则对应rmb汇率为1
            $("#rmbRate").val(1);
            $("#usdRate").val(usdRate);
        }else if(englishName == "USD"){
            //如果选择美元，则对应美金汇率为1
            $("#rmbRate").val(rmbRate);
            $("#usdRate").val(1);
        }else{
            //其它
            let exchangeRate = getCurrencyInfoByCode(data.value, 3);
            $("#usdRate").val(exchangeRate);
            $("#rmbRate").val(rmbRate);
        }
        let name = getCurrencyInfoByCode(data.value, 2);
        $("#currency").val(name);
    })

    //获取币种信息：code:编码  type(1:获取英文名称 2:获取name 3:获取汇率)
    function getCurrencyInfoByCode(code, type){
        for(let i in currencyInfo){
            if(currencyInfo[i].code == code){
                let res = "";
                switch (type) {
                    case 1:
                        res = currencyInfo[i].englishName;
                        break;
                    case 2:
                        res = currencyInfo[i].name;
                        break;
                    case 3:
                        res = currencyInfo[i].exchangeRate;
                        break;
                }
                return res;
            }
        }
        return "";
    }

    //监听制单公司下拉框
    form.on("select(companyCode)", function(data){
        if(data.value === ""){
            return;
        }
        let name = getCompanyInfoByCode(data.value);
        $("#companyName").val(name);

    });

    function getCompanyInfoByCode(code){
        for(let i in companyInfo){
            if(companyInfo[i].code == code){
                return companyInfo[i].name;
            }
        }
        return "";
    }




    //监听收款单位下拉框
    form.on("select(supplierCode)", function (data) {
        let select_text = data.elem[data.elem.selectedIndex].text;
        $("#supplierName").val(select_text);
        $("#supplierCode").next().find("dl").css({"display": "none"});

        $('#bankName').empty();
        $('#bankAccount').empty();
        //为收款银行和收款账号赋值
        getBankInfoData(data.value);
        form.render();
    });

    //为收款银行和收款账号赋值
    function getBankInfoData(code){
        //获取银行信息
        $.ajax({
            url:"payment/getBankInfo?code="+code,
            success:function(data){
                if(data.status == 200){
                    bankList = data.data;
                    $('#bankName').empty();
                    $('#bankAccount').empty();
                    for(let i in data.data){
                        $('#bankName').append(new Option(data.data[i].bankName, data.data[i].bankName));
                        $('#bankAccount').append(new Option(data.data[i].bankAccount, data.data[i].bankAccount));
                    }
                    form.render('select');
                }
            }
        });
    }

    $(document).on('input propertychange', "#supplierName", (function () {
        let values = $("#supplierName").val();
        $("#supplierCode").val(values);
        form.render();
        $("#supplierCode").next().find("dl").css({"display": "block"});
        let dl = $("#supplierCode").next().find("dl").children();
        let j = -1;
        for (var i = 0; i < dl.length; i++) {
            if (dl[i].innerHTML.indexOf(values) <= -1) {
                dl[i].style.display = "none";
                j++;
            }
            if (j == dl.length - 1) {
                $("#supplierCode").next().find("dl").css({"display": "none"});
            }
        }
    }));

    //监听收款银行下拉框
    form.on("select(bankName)", function (data) {
        let name = data.value;
        if(isEmpty(name)){
            return;
        }
        let bankAccount = getAccountByName(name);
        if(isEmpty(bankAccount)){
            return;
        }
        $('#bankAccount').val(bankAccount);
        form.render('select');
    });

    //监听收款账号下拉框
    form.on("select(bankAccount)", function (data) {
        let account = data.value;
        if(isEmpty(account)){
            return;
        }
        let bankName = getNameByAccount(account);
        if(isEmpty(bankName)){
            return;
        }
        $('#bankName').val(bankName);
        form.render('select');
    });

    function getAccountByName(name){
        for(let i in bankList){
            if(name == bankList[i].bankName){
                return bankList[i].bankAccount;
            }
        }
        return "";
    }

    function getNameByAccount(account){
        for(let i in bankList){
            if(account == bankList[i].bankAccount){
                return bankList[i].bankName;
            }
        }
        return "";
    }

//监听提交
    form.on('submit(form-element)', function (data) {
        if (checkData() == 0) {
            let req = getSave(data);
            req["saveType"] = 1;
            let result = JSON.stringify(req);
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:result,
                url:"payment/add",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("保存成功", {icon: 6});
                        setTimeout(function () {
                            //保存成功则刷新提交过来的界面 并关闭此页面
                            parent.detab("views/jsp/Money/payment.jsp");
                            parent.intab("views/jsp/Money/payment.jsp", "付款")
                            parent.detab("views/jsp/Money/tpl/newuppayment.jsp" + (id == '' ? '' : '?id=' + id));
                        }, );
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                    return false;
                }
            });
        }
        return false;
    });
    form.on('submit(form-element2)', function (data) {
        if (checkData() == 0) {
            let req = getSave(data);
            req["saveType"] = 2;
            let result = JSON.stringify(req);
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:result,
                url:"payment/add",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("提交审批成功", {icon: 6});
                        setTimeout(function () {
                            //保存成功则刷新提交过来的界面 并关闭此页面
                            parent.detab("views/jsp/Money/payment.jsp");
                            parent.intab("views/jsp/Money/payment.jsp", "付款")
                            parent.detab("views/jsp/Money/tpl/newuppayment.jsp" + (id == '' ? '' : '?id=' + id));
                        }, );
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                    return false;
                }
            });

        }
        return false;
    });

    function checkData() {
        let indexsl = 0;
        let maininformationdata = table.cache["maininformationtableid"];
        $.each(maininformationdata, function (index, value) {
            let applicationAmount = maininformationdata[index]["applicationAmount"];
            let amountsPayable = maininformationdata[index]["amountsPayable"];
            let cVal = new BigNumber(applicationAmount).comparedTo(new BigNumber(amountsPayable));
            if(cVal == 1){
                layer.msg("付款明细表第" + (index + 1) + "条申请金额不能超过应付金额");
                indexsl++;
                return false;
            }
            if (typeof (maininformationdata[index]["applicationAmount"]) === "undefined" || maininformationdata[index]["applicationAmount"] === "") {
                layer.msg("付款明细表第" + (index + 1) + "条申请金额不能为空");
                indexsl++;
                return false;
            } else if (typeof (maininformationdata[index]["typeCode"]) === "undefined" || maininformationdata[index]["typeCode"] === "") {
                layer.msg("付款明细表第" + (index + 1) + "条付款类型不能为空");
                indexsl++;
                return false;
            } else if (typeof (maininformationdata[index]["berPersonCode"]) === "undefined" || maininformationdata[index]["berPersonCode"] === "") {
                layer.msg("付款明细表第" + (index + 1) + "条承担人员不能为空");
                indexsl++;
                return false;
            } else if (typeof (maininformationdata[index]["purchaseNo"]) === "undefined" || maininformationdata[index]["purchaseNo"] === "") {
                layer.msg("付款明细表第" + (index + 1) + "条采购单号不能为空");
                indexsl++;
                return false;
            }

        });

        return indexsl;
    }

    function getSave(data){
        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        req["type"] = type;
        //获取明细数据
        let detailList = table.cache["maininformationtableid"];
        req["detailList"] = detailList;

        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];

        req["annexList"] = annexReqs;

        return req;
    }

    /**
     * 获取是否含税
     * @param val
     * @returns {string}
     */
    function getIsTaxIncluded(val){
        let res = "";
        if(isEmpty(val)){
            return res;
        }
        switch (val) {
            case 1:
                res = "含税出厂价";
                break;
            case 2:
                res = "未税出厂价";
                break;
            case 3:
                res = "含税FOB";
                break;
            case 4:
                res = "未税FOB价";
                break;
        }
        return res;
    }

    table.render({
        elem: '#maininformation',
        id: 'maininformationtableid',
        data: detailList,
        toolbar: '#maininformationtoolbar',
        totalRow: true,
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
            {field: 'invoiceNumber', width: 120, title: '发票号码', sort: true},
            {field: 'contractNo', width: 120, title: '外销合同号', sort: true},
            {field: 'purchaseNo', width: 120, title: '采购单号', sort: true},
            {field: 'typeCode', width: 280, title: '付款类型', templet: '#paymenttypeselect'},
            {field: 'isTaxIncluded', width: 120, title: '是否含税', templet: function (data) {return getIsTaxIncluded(data["isTaxIncluded"]);}},
            {field: 'berPersonCode', width: 180, title: '承担人员', templet: '#undertakepersonnelselect'},
            {field: 'amountsPayable', width: 120, title: '应付金额', sort: true, totalRow: true},
            {field: 'applicationAmount', width: 120, title: '申请金额', edit: 'text', totalRow: true},
            {field: 'totalApplication', width: 120, title: '已申请合计', sort: true, totalRow: true},
            {field: 'claimAmount', width: 120, title: '索赔金额', edit: 'text', totalRow: true},
            {field: 'allocatedAmount', width: 120, title: '已分摊金额', sort: true, totalRow: true},
            {field: 'unallocatedAmount', width: 120, title: '未分摊金额', sort: true, totalRow: true},
            {field: 'purchasePaidAmount', width: 120, title: '采购已付款金额', sort: true, totalRow: true},
            {field: 'totalPurchaseAmount', width: 120, title: '采购合同总额', sort: true, totalRow: true},
            {field: 'totalInvoiceAmount', width: 120, title: '发票合同总额', sort: true, totalRow: true},
            {field: 'invoicePaidAmount', width: 120, title: '发票已付款金额', sort: true, totalRow: true},
            {field: 'specialNote', width: 80, title: '特殊备注', edit: 'text'},
            {field: 'carryDate', width: 120, title: '出运日期', sort: true},
            {field: 'customerCode', width: 120, title: '客户代码', sort: true},
            {field: 'saleAmountReceived', width: 120, title: '外销已收款金额', sort: true, totalRow: true},
            {field: 'supplierAccountPeriod', width: 120, title: '供应商账期', sort: true},
            {field: 'saleAccountPeriod', title: '外销客户账期', width: 120},
            {field: 'priceTermsName', title: '外销价格术语', width: 120},
        ]],
        height: 380
        ,page: false
        ,limit: Number.MAX_VALUE
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            //付款类型
            for(let i in paymentTypeList){
                $(".paymentType").append("<option value=\"" + paymentTypeList[i].code + "\">" + paymentTypeList[i].name + "</option>");
            }
            //承担人员
            for(let i in userList){
                $(".berPersonCode").append("<option value=\"" + userList[i].code + "\">" + userList[i].name + "</option>");
            }
            //付款金额 = 明细申请金额合计
            let amount = new BigNumber(0);
            for (var i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                //申请金额
                let applicationAmount = res.data[i].applicationAmount;
                amount = amount.plus(new BigNumber(applicationAmount))
                //付款类型编码
                let typeCode = res.data[i].typeCode;
                if(!isEmpty(typeCode)){
                    $("#paymentType_" + tempId).val(typeCode);
                    for(let j in paymentTypeList){
                        if(paymentTypeList[j].code == typeCode){
                            res.data[i]["typeName"] = paymentTypeList[j].name;
                        }
                    }
                }else {
                    $("#paymentType_" + tempId).val(paymentTypeList[0].code);
                    res.data[i]["typeCode"] = paymentTypeList[0].code;
                    res.data[i]["typeName"] = paymentTypeList[0].name;
                }

                //承担人员编码
                let berPersonCode = res.data[i].berPersonCode;
                if(!isEmpty(berPersonCode)){
                    $("#berPersonCode_" + tempId).val(berPersonCode);
                    res.data[i]["berPersonCode"] = berPersonCode;
                    res.data[i]["berPersonName"] = res.data[i].berPersonName;
                }else {
                    $("#berPersonCode_" + tempId).val(userList[0].code);
                    res.data[i]["berPersonCode"] = userList[0].code;
                    res.data[i]["berPersonName"] = userList[0].name;
                }
            }
            let num = amount.dp(4, BigNumber.ROUND_HALF_UP).toString();
            $("#amount").val(num);
            if(res.data.length > 0){
                //如果主表收款单位为空,则默认选择明细第一条数据的收款单位
                let val = $("[name='supplierCode']").val()
                if(isEmpty(val)){
                    //获取供应商名称
                    let supplierName = res.data[0].supplierName;
                    let code = "";
                    for(let i in supplierList){
                        if(supplierList[i].name == supplierName){
                            code = supplierList[i].code;
                            $("#supplierCode").val(code);
                            break;
                        }
                    }
                    if(code.length > 0){
                        $("#supplierName").val(supplierName);
                        $("#supplierCode").next().find("dl").css({"display": "none"});
                        getBankInfoData(code);
                    }
                }
                //默认选择明细第一条数据的制单公司
                let signedCompanyCode = res.data[0].signedCompanyCode;
                $("#companyCode").val(signedCompanyCode);
                $("#companyName").val(res.data[0].signedCompanyName);
                //付款类型
                type = res.data[0].type;
            }
            form.render();
        }
    });

    function isEmpty(data){
        if(data == undefined || data == "" || data == null){
            return true;
        }
        return false;
    }

    form.on("select(typeCodeSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataindex = elem.attr("data-index");
        let tabledata = table.cache["maininformationtableid"];
        $.each(tabledata, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataindex) {
                tabledata[index]["typeCode"] = data.value;
                tabledata[index]["typeName"] = getTypeName(data.value);
            }
        });
    });

    function getTypeName(code){
        for(let i in paymentTypeList){
            if(paymentTypeList[i].code == code){
                return paymentTypeList[i].name;
            }
        }
        return "";
    }

    form.on("select(berPersonCodeSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataindex = elem.attr("data-index");
        let tabledata = table.cache["maininformationtableid"];
        $.each(tabledata, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataindex) {
                tabledata[index]["berPersonCode"] = data.value;
                tabledata[index]["berPersonName"] = getNameByCode(data.value);
            }
        });
    });

    function getNameByCode(code){
        for(let i in userList){
            if(userList[i].code == code){
                return userList[i].name;
            }
        }
        return "";
    }

    function productTableReload(){
        table.reload('maininformationtableid',{
            data:table.cache.test,
            totalRow: true,
        })
    }

    table.on('edit(maininformationtable)', function (obj) {
        //旧值
        let old = $(this).prev().text();
        //判断数据类型 ,,,,,,,
        if ((obj.field == "applicationAmount" || obj.field == "claimAmount") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        if(obj.field == "applicationAmount"){
            //申请金额不能大于应付金额
            //应付金额
            let amountsPayable = obj.data.amountsPayable;
            if(obj.value > amountsPayable){
                layer.msg("申请金额不能超过应付金额", {icon: 5});
                return;
            }
            //更新主表付款金额
            let amount = $("#amount").val();
            let newAmount = new BigNumber(amount).minus(old).plus(new BigNumber(obj.value)).dp(4, BigNumber.ROUND_HALF_UP).toString();
            $("#amount").val(newAmount);
            form.render();
        }

        //表单重载
        productTableReload();

    });


    table.on('toolbar(maininformationtable)', function (obj) {
        let tableData = table.cache["maininformationtableid"];
        let type = 0;
        if(tableData.length > 0){
            type = tableData[0]["type"];
        }
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'registeradvancepayment':
                if(2 == type){
                    layer.msg('已登记货款，无法再登记预付款');
                    break;
                }
                layer.open({
                    type: 2,
                    area: ['80%', '95%'],
                    content: 'views/jsp/Money/tpl/registeradvancepaymentfk.jsp'
                });
                break;
            case 'registrationpayment':
                if(1 == type){
                    layer.msg('已登记预付款，无法再登记货款');
                    break;
                }
                layer.open({
                    type: 2,
                    area: ['80%', '95%'],
                    content: 'views/jsp/Money/tpl/registrationpayment.jsp'
                });
                break;
            case 'registrationSample':
                if(2 == type){
                    layer.msg('已登记货款，无法再登记样品付款');
                    break;
                }
                layer.open({
                    type: 2,
                    area: ['80%', '95%'],
                    content: 'views/jsp/Money/tpl/registrationSample.jsp'
                });
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确认删除？', confirmInfo(3,6), function (index) {
                        let cbList = table.cache["maininformationtableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("maininformationtableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName',event:'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        } else if (obj.event === 'fileName'){
            onLineFile(data.filePath);
        }
    });

    //---操作日志
    let logData = [];
    table.render({
        elem: '#otherwarehouselog'
        , data: logData
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    function isNumber(val) {
        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }


    //时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
    function getNowFormatDate(type) {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if(1 == type){
            let currentDate = year + separator + month + separator + strDate;
            return currentDate;
        }else if(2 == type){
            let second = date.getMilliseconds().toString();
            if(second.length < 3){
                if(second.length == 1){
                    second = "0" + "0" + second;
                }else {
                    second = "0" + second;
                }
            }
            let currentDate = year.toString() + month.toString() + strDate.toString() + second;
            return currentDate;
        }

    }

    let currentDate = getNowFormatDate(1);
    //应付日期
    laydate.render({
        elem: '#time',
        value: currentDate,
        isInitValue: true
    });
    //创建日期
    laydate.render({
        elem: '#createDate',
        value: currentDate,
        isInitValue: true,
        min: currentDate,
        max: currentDate
    });

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }


});